<script setup lang="ts">
import { ref, onMounted, onUpdated } from 'vue'
import DataTable from 'datatables.net-vue3'
import DataTablesCore from 'datatables.net-bs4'
import 'datatables.net-select'
import '../../plugin/datatables.net-responsive'
import { db } from '../../db/db'
import { getUsers } from '../../util/SessionUtil'
import $ from 'jquery'

DataTable.use(DataTablesCore)

const options: any = {
    responsive: true,
    select: true,
    aaSorting: [[3, 'desc']],// 排序
    language: {
        "sProcessing": "处理中...",
        "sLengthMenu": "显示 _MENU_ 项结果",
        "sZeroRecords": "没有匹配结果",
        "sInfo": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
        "sInfoEmpty": "显示第 0 至 0 项结果，共 0 项",
        "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
        "sInfoPostFix": "",
        "sSearch": "搜索:",
        "sUrl": "",
        "sEmptyTable": "表中数据为空",
        "sLoadingRecords": "载入中...",
        "sInfoThousands": ",",
        "oPaginate": {
            "sFirst": "首页",
            "sPrevious": "<",
            "sNext": ">",
            "sLast": "末页"
        },
        "oAria": {
            "sSortAscending": ": 以升序排列此列",
            "sSortDescending": ": 以降序排列此列"
        },
        "select": {
            "rows": {
                _: '选择了 %d 行',
                1: '选择了 1 行'
            }
        }
    },
    autoWidth: true
}

const tableData: any = ref([])

const columns = [
    { data: 'commentId', title: '评论ID', responsivePriority: 11, className: 'none' },
    {
        data: 'commentContent', title: '内容', responsivePriority: 1
    },
    { data: 'salvationId', title: '救助ID', responsivePriority: 4, className: 'never' },
    { data: 'commentDate', title: '评论时间', responsivePriority: 3 },
    { data: null, title: '操作', responsivePriority: 2, render: '#operate' },
]

let dt
const table = ref()

const users = getUsers()

const loadTableData = async () => {
    tableData.value = await db.comment.where('username').equals(users.username).toArray()
}

onMounted(async () => {
    loadTableData()
})

onUpdated(() => {
    // 因异步加载数据，导致宽度变化，需要重画
    dt = table.value.dt
    dt.columns.adjust().draw()
    $('.carousel').carousel()

    $('.datatable').off('click', '.lookDetail').on("click", '.lookDetail', function (e: any) {
        lookDetail(e.currentTarget.dataset.id)
    })

    $('.datatable').off('click', '.lookTimeline').on("click", '.lookTimeline', function (e: any) {
        lookTimeline(e.currentTarget.dataset.id)
    })

    $('.datatable').off('click', '.del').on("click", '.del', function (e: any) {
        del(e.currentTarget.dataset.id)
    })

})

const tipModal = ref({
    class: '',
    title: '',
    content: ''
})

const confirmModal = ref({
    class: '',
    title: '',
    content: '',
    callBack: '',
    data: {}
})


const del = (commentId: string) => {

    confirmModal.value.class = 'text-danger'
    confirmModal.value.title = '删除确认'
    confirmModal.value.content = '您好，确认进行删除吗？'
    confirmModal.value.callBack = 'del'


    confirmModal.value.data = {
        commentId: commentId
    }
    $('#confirmModal').modal('show')
}

const confirmEx = (callBack: string, data: any) => {
    $('#confirmModal').modal('hide')

    if (callBack === 'del') {
        db.comment.where('commentId').equals(data.commentId).delete()
        tipModal.value.class = 'text-success'
        tipModal.value.title = '删除成功'
        tipModal.value.content = '您好，评论已删除！'
        $('#tipModal').modal('show')
    }
    loadTableData()
}

const detailModal = ref({
    content: '',
    images: new Array<any>()
})
const lookDetail = async (salvationId: string) => {
    const salvationData = await db.salvation.where('salvationId').equals(salvationId).toArray()
    const data = salvationData.filter((sd: any) => {
        return sd.salvationId == salvationId
    })
    detailModal.value.content = data[0].petSituation
    const petImage: any = await db.petImage.where('salvationId').equals(salvationId).toArray()
    detailModal.value.images = petImage
    $('#detailModal').modal('show')
}


let petSalvationPlanData: any = ref([])

const lookTimeline = async (salvationId: string) => {
    let tempUpdateData = []
    const tempData = await db.petSalvationPlan.where('salvationId').equals(salvationId).reverse().sortBy('petSalvationPlanDate')
    for (let i = 0; i < tempData.length; i++) {
        let organizeName = ''
        if (tempData[i] && tempData[i].organizeId) {
            const organize: any = await db.organize.where('organizeId').equals(Number(tempData[i].organizeId)).toArray()
            organizeName = organize[0].organizeName
        }

        tempUpdateData.push({
            petSalvationPlanId: tempData[i].petSalvationPlanId,
            node: tempData[i].node,
            situation: tempData[i].situation,
            organizeId: tempData[i].organizeId,
            salvationId: tempData[i].salvationId,
            petSalvationPlanDate: tempData[i].petSalvationPlanDate,
            organizeName: organizeName
        })

    }

    petSalvationPlanData.value = tempUpdateData

    $('#timelineModal').modal('show')
}

</script>
<template>
    <div class="col-md-9 col-lg-10">
        <div class="br-pagebody mg-t-5 pd-x-30">
            <div class="br-section-wrapper">
                <div class="row">
                    <div class="col-md-12">
                        <DataTable :options="options" :data="tableData" :columns="columns"
                            class="table responsive nowrap" ref="table">
                            <template #operate="props">
                                <div class="btn-group" role="group" aria-label="Basic example">
                                    <button type="button" class="btn btn-info btn-sm lookDetail"
                                        :data-id="props.rowData.salvationId">详情</button>
                                    <button type="button" class="btn btn-primary btn-sm lookTimeline"
                                        :data-id="props.rowData.salvationId">进度</button>
                                    <button type="button" class="btn btn-danger btn-sm del"
                                        :data-id="props.rowData.commentId">删除</button>
                                </div>
                            </template>
                        </DataTable>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Modal -->
    <div class="modal fade" id="tipModal" tabindex="-1" aria-labelledby="tipModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" :class="tipModal.class" id="tipModalLabel">{{ tipModal.title }}</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    {{ tipModal.content }}
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">确定</button>
                </div>
            </div>
        </div>
    </div>

    <!--确认Modal-->
    <div class="modal fade" id="confirmModal" tabindex="-1" aria-labelledby="confirmModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" :class="confirmModal.class" id="confirmModalLabel">{{ confirmModal.title }}
                    </h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    {{ confirmModal.content }}
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary"
                        @click="confirmEx(confirmModal.callBack, confirmModal.data)">确定</button>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="detailModal" tabindex="-1" aria-labelledby="detailModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="detailModalLabel">查看详情
                    </h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <p class="mb-1">
                        {{ detailModal.content }}
                    </p>

                    <div id="carouselExampleControls" class="carousel slide" data-ride="carousel">
                        <div class="carousel-inner">
                            <div class="carousel-item" v-for="(item, index) in detailModal.images"
                                :class="index == 0 ? 'active' : ''">
                                <img :src="item.petImageUrl" class="d-block w-100" alt="宠物图片">
                            </div>
                        </div>
                        <button class="carousel-control-prev" type="button" data-target="#carouselExampleControls"
                            data-slide="prev">
                            <span class="carousel-control-prev-icon" aria-hidden="true"></span>
                            <span class="sr-only">Previous</span>
                        </button>
                        <button class="carousel-control-next" type="button" data-target="#carouselExampleControls"
                            data-slide="next">
                            <span class="carousel-control-next-icon" aria-hidden="true"></span>
                            <span class="sr-only">Next</span>
                        </button>
                    </div>

                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="timelineModal" tabindex="-1" aria-labelledby="timelineModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="timelineModalLabel">查看进度
                    </h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="container">
                        <ul class="timeline">
                            <li class="timeline-item" v-for="item in petSalvationPlanData"
                                :key="item.petSalvationPlanId">
                                <div class="timeline-badge" style="background-color:#4189c9"><font-awesome-icon
                                        icon="check" /></div>
                                <div class="timeline-panel">
                                    <div class="timeline-heading">
                                        <h6>{{ item.petSalvationPlanDate }}</h6>
                                    </div>
                                    <div class="timeline-body">
                                        <p>节点：{{ item.node }}</p>
                                        <p>状况：{{ item.situation }}</p>
                                        <p>救助组织：{{ item.organizeName }}</p>
                                    </div>
                                </div>
                            </li>
                            <!-- 更多时间点... -->
                        </ul>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>
</template>
<style>
@import 'datatables.net-bs4';

.timeline {
    list-style: none;
    padding: 20px 0;
    position: relative;
}

.timeline:before {
    content: '';
    position: absolute;
    top: 0;
    bottom: 0;
    width: 5px;
    background: #eee;
    left: 50%;
    margin-left: -2.5px;
}

.timeline-item {
    margin-bottom: 20px;
    position: relative;
}

.timeline-item:before,
.timeline-item:after {
    content: '';
    display: table;
}

.timeline-item:after {
    clear: both;
}

.timeline-badge {
    color: white;
    width: 50px;
    height: 50px;
    line-height: 50px;
    font-size: 14px;
    text-align: center;
    position: absolute;
    top: 0;
    left: 50%;
    margin-left: -25px;
    background-color: #6c757d;
    border-radius: 50%;
    z-index: 100;
}

.timeline-body {
    margin-left: 0px;
    margin-right: 15px;
    background-color: #fff;
    border: 1px solid #ddd;
    border-radius: 4px;
    padding: 15px;
    position: relative;
}
</style>